package com.ruoyi.framework.web.service;

import com.alibaba.fastjson2.JSONObject;

import com.ruoyi.common.core.domain.entity.MemberUser;
import com.ruoyi.common.core.domain.model.LoginAppUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.member.service.IMemberUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class AppLoginService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private AppTokenService appTokenService;
    @Resource
    private IMemberUserService appUserService;
    @Value("${weChat.minApp.appId}")
    private String miniAppId;
    @Value("${weChat.minApp.appSecret}")
    private String miniAppSecret;

//    @Value("${weChat.mp.appId}")
    private String mpAppId ="wx4636c14a03145741";
//    @Value("${weChat.mp.appSecret}")
    private String mpAppSecret ="87ac4bf46b9b52e63afdc3a97f81c306";

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    public String login(String username, String password) {
        MemberUser appUser = appUserService.selectAppUserByUserName(username);
        if (appUser == null) {
            throw new ServiceException("用户不存在");
        }
        if (!appUserService.checkPassword(password, appUser.getSalt(), appUser.getPassword())) {
            throw new ServiceException("密码不正确");
        }
        LoginAppUser loginAppUser = new LoginAppUser(appUser.getUserId(), appUser);
        recordLoginInfo(appUser);
        // 生成token
        return appTokenService.createAppToken(loginAppUser);
    }
    public String moni(String openId){
        //1根据code获取公众号的access_token和openid

        //2根据openId判断用户是否存在 不存在自动注册 openId对应数据库表user_name
        MemberUser appUser = appUserService.selectAppUserByOpenId( openId);
        if (appUser == null) {
            appUser = new MemberUser();
            appUser.setUserName("微信用户");
            appUser.setOpenId(openId);
            appUserService.insertAppUser(appUser);
        }
        //3生成token
        LoginAppUser loginAppUser = new LoginAppUser(appUser.getUserId(), appUser);
        recordLoginInfo(appUser);
        return appTokenService.createAppToken(loginAppUser);
    }
    /**
     * 公众号登录
     * @param code
     * @return
     */
    public String mpLogin(String code){
        //1根据code获取公众号的access_token和openid
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", mpAppId).replace("{1}", mpAppSecret).replace("{2}", code);
        System.out.println(replaceUrl);
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(replaceUrl));
        if(jsonObject.get("errcode") != null){
            throw new ServiceException(String.format("获取微信授权信息失败，错误编码：%s，错误信息：%s", String.valueOf(jsonObject.get("errcode")), (String)jsonObject.get("errmsg")));
        }
        //2根据openId判断用户是否存在 不存在自动注册 openId对应数据库表user_name
        MemberUser appUser = appUserService.selectAppUserByOpenId(String.valueOf(jsonObject.get("openid")));
        if (appUser == null) {
            appUser = new MemberUser();
            appUser.setUserName("微信用户");
            appUser.setOpenId(String.valueOf(jsonObject.get("openid")));
            appUser.setRegisterIp(IpUtils.getIpAddr());
            appUser.setRegisterTime(DateUtils.getNowDate());
            appUserService.insertAppUser(appUser);
        }
        //3生成token
        LoginAppUser loginAppUser = new LoginAppUser(appUser.getUserId(), appUser);
        recordLoginInfo(appUser);
        return appTokenService.createAppToken(loginAppUser);
    }
    public String mpLoginOpenId(String code){
        //1根据code获取公众号的access_token和openid
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}", mpAppId).replace("{1}", mpAppSecret).replace("{2}", code);
        System.out.println(replaceUrl);
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(replaceUrl));
        if(jsonObject.get("errcode") != null){
            throw new ServiceException(String.format("获取微信授权信息失败，错误编码：%s，错误信息：%s,mpAppId: %s ,mpAppSecret: %s",
                    String.valueOf(jsonObject.get("errcode")), (String)jsonObject.get("errmsg"),mpAppId,mpAppSecret));
        }
       return String.valueOf(jsonObject.get("openid"));
    }


    /**
     * 小程序登录
     * @param code
     * @return
     */
    public String minLogin(String code) {
        //1根据code执行小程序登录获取 openId
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}",miniAppId).replace("{1}",miniAppSecret).replace("{2}",code);
        System.out.println(replaceUrl);
        JSONObject jsonObject = JSONObject.parseObject(HttpUtils.sendGet(replaceUrl));
        if(jsonObject.get("errcode")!=null){
            throw new ServiceException(String.format("获取微信授权信息失败，错误编码：%s，错误信息：%s",String.valueOf(jsonObject.get("errcode")),(String)jsonObject.get("errmsg")));
        }
        //2根据openId判断用户是否存在 不存在自动注册 openId对应数据库表user_name
        MemberUser appUser = appUserService.selectAppUserByOpenId(String.valueOf(jsonObject.get("openid")));
        if (appUser == null) {
            appUser = new MemberUser();
            appUser.setUserName("微信用户");
            appUser.setOpenId(String.valueOf(jsonObject.get("openid")));
            appUser.setRegisterIp(IpUtils.getIpAddr());
            appUser.setRegisterTime(DateUtils.getNowDate());
            appUserService.insertAppUser(appUser);
        }
        //3生成token
        LoginAppUser loginAppUser = new LoginAppUser(appUser.getUserId(), appUser);
        recordLoginInfo(appUser);
        return appTokenService.createAppToken(loginAppUser);
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    private void recordLoginInfo(MemberUser appUser) {

        appUser.setLoginIp(IpUtils.getIpAddr());
        appUser.setLoginDate(DateUtils.getNowDate());
        appUserService.updateAppUser(appUser);
    }

}
